﻿using System;
using System.Collections.Generic;
using System.ServiceModel;
using WcfService1.DTO;
using System.Linq;

namespace WcfService1
{
    [ServiceContract]
    public class AplicationStateServices
    {
        [OperationContract]
        public bool IsTransactionUsed(string transactionNumber, UserDTO user)
        {
            if (string.IsNullOrEmpty(transactionNumber)) return false;

            bool res = false;
            if (WCFCache.Current[transactionNumber] != null)
            {
                res = true;
            }
            else
            {
                if (transactionNumber.Contains("|"))InsertTransactionNumber(transactionNumber);
                WCFCache.Current.Insert(transactionNumber, user.UserID);
            }
            return res;
        }

        [OperationContract]
        public void ClearTransaction(string transactionNumber, UserDTO user)
        {
            if (string.IsNullOrEmpty(transactionNumber)) return;

            if (WCFCache.Current[transactionNumber] != null)
                WCFCache.Current.Remove(transactionNumber);
        }


        [OperationContract]
        public void ClearTransactionUnexpected(UserDTO user)
        {
            string keyToRemove = string.Empty ; 
            foreach (var key in WCFCache.Current.CachedItems.Keys)
            {
                if (WCFCache.Current[key].ToString() == user.UserID.ToString())
                    keyToRemove = key.ToString();
            }

            WCFCache.Current.Remove(keyToRemove);
        }

        private void InsertTransactionNumber(string transactionType)
        {
            string LastNumber = transactionType.Split(new string[] {"|"}, StringSplitOptions.None).LastOrDefault();
            WCFCache.Current.Insert(transactionType,LastNumber);
        }
    }
}